package erfgame.frontend.desktop.view.terrain.iso.interaction;

import java.util.ArrayList;
import java.util.List;

import erfgame.core.Filter;
import erfgame.core.Point3D;
import erfgame.core.entity.Entity;

public class FilteringEntityInteractionDescriptionFactory implements
		EntityInteractionDescriptionFactory {

	private List<FilteringEntityInteractionDescriptionEntry> filters;
	
	public FilteringEntityInteractionDescriptionFactory(
			List<FilteringEntityInteractionDescriptionEntry> filters
	) {
		this.filters = filters;
	}
	
	public List<InteractionDescription> getInteractions(Entity e, Point3D p) {
		ArrayList<InteractionDescription> result;
		result = new ArrayList<InteractionDescription>();
		for( int i=0; i<this.filters.size(); i++ ) {
			FilteringEntityInteractionDescriptionEntry entry;
			entry = filters.get( i );
			Filter<Entity> filter = entry.getFilter();
			if( filter.accept(e) ) {
				entry.getChildInteractionsFactory();
				
				InteractionDescription prototype;
				prototype = entry.getInteractionDescriptionPrototype();
				
				EntityInteractionDescriptionFactory childInteractionFactory;
				childInteractionFactory = entry.getChildInteractionsFactory();
				
				List<InteractionDescription> children = new ArrayList<InteractionDescription>();
				// TODO : ordering of filtered and unfiltered child elements??
				if( prototype.getChildren() != null ) {
					children.addAll( prototype.getChildren() );
				}
				if( childInteractionFactory != null ) {
					children = childInteractionFactory.getInteractions(e, p);
				}
				
				InteractionDescription description;
				description = new InteractionDescription(
						prototype.getId(),
						prototype.getName(),
						prototype.getDescription(),
						prototype.getRenderer(),
						prototype.getInteractionFactory(),
						children
				);
				result.add( description );
			}
		}
		return result;
	}

}
